package platform

import (
	"log"
	"sync"
	"uselesscapslock/config"
)

type KeyboardManager struct {
	hook   *KeyboardHook
	config *config.Config
	mutex  sync.RWMutex
}

var (
	manager *KeyboardManager
	once    sync.Once
)

func GetKeyboardManager() *KeyboardManager {
	once.Do(func() {
		hook := NewKeyboardHook()
		manager = &KeyboardManager{
			hook: hook,
		}
		hook.manager = manager
	})
	return manager
}

func (km *KeyboardManager) Start() error {
	// 加载配置
	cfg, err := config.LoadConfig()
	if err != nil {
		return err
	}

	km.mutex.Lock()
	km.config = cfg
	km.mutex.Unlock()

	// 启动键盘钩子
	return km.hook.Start()
}

func (km *KeyboardManager) Stop() {
	km.hook.Stop()
}

func (km *KeyboardManager) ReloadConfig() error {
	cfg, err := config.LoadConfig()
	if err != nil {
		return err
	}

	km.mutex.Lock()
	km.config = cfg
	km.mutex.Unlock()

	log.Println("键盘映射配置已重新加载")
	return nil
}
